//
//  ViewController.m
//  HundPark
//
//  Created by Aguilar Rolando on 2013-03-04.
//  Copyright (c) 2013 ARV IT. All rights reserved.
//


#import "TableViewController.h"
#import "UIImageView+AFNetworking.h"
#import "TDBadgedCell.h"
#import "UIColor+HundPark.h"

@interface TableViewController ()

@property(weak,nonatomic) City *allParks;
@property(strong,nonatomic) NSMutableArray *geoFences;

-(void)refreshCurrentLocation:(id *)sender;
@end

@implementation TableViewController{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
    UIRefreshControl *refreshControl;
    CustomProgressView *customProgressView;
}

@synthesize tableView =_tableView;
@synthesize allParks = _allParks;
@synthesize geoFences = _geoFences;

#define FILESERVERURL @"http://hundapp.byethost8.com/parkImages/"
#define GEOFENCE_RADIUS 250.0

#pragma mark - Lazy Instantiation
-(City *)allParks
{
    if(!_allParks){
        AppDelegate *appDelegate =  (AppDelegate *)[[UIApplication sharedApplication ]delegate];
        _allParks = appDelegate.allParks;
    }
    
    return _allParks;
}

// Create geoFence object of park objects
-(NSMutableArray *)geoFences
{
    if(!_geoFences){
        _geoFences = [[NSMutableArray alloc] init];
        
        //For all parks in City Array Class create geoFence
        for (Park *parks in self.allParks.parks) {
            // Create geoFence objects
            CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter:parks.coordinate
                                                                       radius:GEOFENCE_RADIUS
                                                                   identifier:parks.name];
            [_geoFences addObject:region];
        }
    }
    return _geoFences;
}


#pragma mark - Life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Setting location mangager
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	
    // ProgressView
    customProgressView = [[CustomProgressView alloc]init];
    customProgressView.titleText = @"Hämtar inställningar";
    [customProgressView.activityIndicator startAnimating];
    
    // Add progess View
    [self.view addSubview:customProgressView];
    
    //Pull to refresh table view
    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self
                       action:@selector(refreshCurrentLocation:)
             forControlEvents:UIControlEventValueChanged];
    
    [self.tableView addSubview:refreshControl];
    
    // now set your Custom label
    CustomNavbarTitleLabelGreen *titleLabel =[[CustomNavbarTitleLabelGreen alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    titleLabel.text = @"Hundparker";
    self.navigationItem.titleView = titleLabel;
}

-(void)viewWillAppear:(BOOL)animated
{
    //Deselect row
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow]
                                  animated:YES];
    
    //Start getting amount of visitor for each park
    [self.allParks getAmountOfVisitors];
    
    // Set a as delegate of City
    self.allParks.delegate = self;
}


- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
}


#pragma mark - City Delegate
- (void)finishedSyncPlist
{
    // Monitor geofences
    for(CLRegion *geofence in self.geoFences) {
        [locationManager startMonitoringForRegion:geofence];
    }
    
    [self.allParks getAmountOfVisitors];
}

-(void)finishedGetAmountOfVisitors
{
    [locationManager startUpdatingLocation];
}


#pragma mark - Tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.allParks.parks count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"Cell";
    TDBadgedCell *cell = (TDBadgedCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    // TODO: Is this needed?
    if (cell == nil) {
        cell = [[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:simpleTableIdentifier];
    }
    
    // Custom Labels for each cell
    UILabel *parkName = (UILabel *)[cell viewWithTag:1];
    UILabel *parkDistric = (UILabel *)[cell viewWithTag:2];
    UILabel *parkDistance = (UILabel *)[cell viewWithTag:3];
    
    // Set up aprk info
    Park *parkForIndex = [self.allParks.parks objectAtIndex:indexPath.row];
    parkName.text = parkForIndex.name;
    parkDistric.text = parkForIndex.distric;
    parkDistance.text = [[NSString stringWithFormat:@"%.1f",parkForIndex.distance/1000] stringByAppendingString:@" km"];
    
    // Set up badge info
	cell.badgeString = parkForIndex.amountOfDogs;
    cell.badgeRightOffset = 188;
    cell.showShadow = YES;

    cell.badgeTextColor = [UIColor whiteColor];
    if ([parkForIndex.amountOfDogs intValue] > 0) {
        cell.badgeColor = [UIColor badgeColorVisted];
        cell.badge.fontSize = 12;
    } else {
        cell.badgeColor = [UIColor badgeColorUnvisted];
        cell.badge.fontSize = 10;
    }
    
    // Set up image
    NSString *imageUrl = [NSString stringWithFormat:@"%@thumb%@.png",FILESERVERURL, parkForIndex.parkId];
    NSURL *url = [NSURL URLWithString:imageUrl];
    [cell.imageView setImageWithURL:url
                   placeholderImage:[UIImage imageNamed:@"storHund.png"]];
    
    return cell;
}


#pragma mark - locationManager delegate - monitoring geofence
// Delegetes for monitoring a geoFence
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    UIAlertView *showRegionAlert = [[UIAlertView alloc] initWithTitle:region.identifier
                                                              message:@"Entering Region"
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
    [showRegionAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
    UIAlertView *showRegionAlert = [[UIAlertView alloc] initWithTitle:region.identifier
                                                              message:@"Exiting Region"
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
    [showRegionAlert show];
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Error"
                               message:@"Failed to Get Your Location"
                               delegate:nil
                               cancelButtonTitle:@"OK"
                               otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    
    NSLog(@"didUpdateToLocation: %@", newLocation);
    
    // CODE FROM: http://stackoverflow.com/questions/4635938/cllocationmanager-and-accuracy-issues-any-experiences
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    
    if (locationAge > 5.0) return;
    
    // test that the horizontal accuracy does not indicate an invalid measurement
    if (newLocation.horizontalAccuracy < 0) return;
    
    // Set retrived, NOT Chached location as currenlocation
    currentLocation = newLocation;
    
    if (currentLocation != nil) {
        
        [self.allParks sortArray:currentLocation];
        //Reload tableView when location is found
        //Stop locationmanager to save battery
        //Stop refreshing
        [self.tableView reloadData];
        [locationManager stopUpdatingLocation];
        [refreshControl endRefreshing];
        
        [customProgressView.activityIndicator stopAnimating];
        [customProgressView removeFromSuperview];
    }
}

// Used for debugging
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
    //NSLog(@"Started monitoring %@ region", region.identifier);
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:@"parkInfoDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        ParkDetailViewController *parkViewController = segue.destinationViewController;
        
        //Create object Park
        Park *selectedPark = [self.allParks.parks objectAtIndex:indexPath.row];
        parkViewController.park = selectedPark;
        
    }
}

#pragma mark - Actions
-(void)refreshCurrentLocation:(id *)sender
{
    [locationManager startUpdatingLocation];
}

@end
